package com.gin.kotlin.no_gay_alliance.adapter.vote

import android.content.Context
import android.util.TypedValue
import android.widget.CompoundButton
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.databinding.ItemOptionVoteBinding
import com.gin.nga.response.vote.VoteOption
import java.util.Locale

/**
 * 投票适配器
 * @property checked 已选中的id
 * @constructor
 */
class VoteVoteAdapter(context: Context, handler: MyHandler, data: MutableList<VoteOption> = mutableListOf()) :
    AbstractBindingRecyclerViewAdapter<ItemOptionVoteBinding, VoteOption>(context, handler, data.map { it.groupIndex }.toSet().size == 1, data),
    CompoundButton.OnCheckedChangeListener {
    var checked = mutableListOf<VoteOption>()
    var maxSelect = 1

    override fun onBindViewHolder(holder: ViewHolder<ItemOptionVoteBinding>, position: Int, b: ItemOptionVoteBinding, dataModel: VoteOption) {
        // 按组染色
        if (!zebraStripe){
            val typedValue = TypedValue()
            val attr: Int = if (dataModel.groupIndex % 2 == 0) R.attr.colorRowLight else R.attr.colorRowDark
            context.theme.resolveAttribute(attr, typedValue, true)
            holder.b.root.setBackgroundColor(typedValue.data)
        }

        // 总人数
        val total = data.filter { it.groupIndex==dataModel.groupIndex }.sumOf { it.count }
        val percent = String.format(Locale.CHINESE, "%.2f", 100.0 * dataModel.countPer)

        b.tvCount.text = "${dataModel.count}票 (${percent}%)"
        b.progressBar.max = total
        b.progressBar.setProgress(dataModel.count, true)

        b.checkBox.text = dataModel.label
        b.checkBox.setOnCheckedChangeListener(null)
        b.checkBox.isChecked = checked.contains(dataModel)
        b.checkBox.tag = dataModel
        b.checkBox.setOnCheckedChangeListener(this)
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        val option = buttonView?.tag as? VoteOption ?: return
        if (isChecked) {
            val selected = checked.count { it.groupIndex == option.groupIndex }

            // 如果超出最大选择数量,提示
            if (selected >= maxSelect) {
                buttonView.isChecked = false
                handler.toast("(每组)最多只能选择 $maxSelect 项")
                return
            }
            checked.add(option)
        } else
            checked.remove(option)
    }
}